let fs = require('fs')
let path = require('path')
let request = require('request')
let Sync = require('../memCacheTools/sync')


let __root__ = process.argv[2] || process.cwd()

// const _datas = JSON.parse(fs.readFileSync("../services-branch-2x/jaychou-datas.json", "utf-8"))

const _datas = JSON.parse(fs.readFileSync(path.join(__root__, "services-branch-2x", "easonChan-datas.json"), "utf-8"))

let channels = _datas.channels

let channelids = []

let channelSync = new Sync()

for (let channelid in channels) {
	let chid = channelid
	channelSync.add(function(next) {
		let ipQS = {
			url: "http://localhost:3000/branch/ec/" + chid + "/index",
			method: "GET",
			qs: {
				localhost: 'ttt',
				admin: '000',
			},
			headers: {
				ultimate: 'ultimate',
				localhost: 'xxx',
				admin: '999'
			}
		}

		request(ipQS, function(err, res, body) {
			// let path = "../views-static/branch/" + chid.toLowerCase() + "_index.html"
			let htmlPath = path.join(__root__, "views-static/branch/", chid.toLowerCase() + "_ec_index.html")
				// let path = chid.toLowerCase() + "_index.html"
			fs.writeFileSync(htmlPath, body, 'utf8')
			next()
		})
	})

	// channelids.push(channelid)
}

// channelids.forEach(function(chid, idx) {

// })


let buildHTML = module.exports = function() {

	channelSync.done(function() {
		console.log("init index HTML done")
	})
}


if(process.argv[3] === 'startHTML'){
	buildHTML()
}